<template>
    <div>
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="120px" class="demo-ruleForm">
            <div class="container">
                <el-row>
                    <el-form-item label="入库来源：">
                        <el-radio-group v-model="ruleForm.inType1" @change="handletab">
                            <el-radio label="采购入库">采购入库</el-radio>
<!--                            <el-radio label="加工入库">加工入库</el-radio>-->
                        </el-radio-group>
                    </el-form-item>
                </el-row>
                <el-row :span="24">
                    <el-col :span="10">
                        <el-form-item label="供应商名称：" v-if="processhidden">
                            <el-select v-model="ruleForm.supplierName" value-key="id" filterable placeholder="请选择" style="width: 300px">
                                <el-option
                                    v-for="item in supplierlist"
                                    :key="item.id"
                                    :label="item.supplierName"
                                    :value="item.supplierName"
                                >
                                    {{ item.supplierName }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="入库时间：">
                            <el-date-picker
                                type="date"
                                placeholder="选择日期"
                                value-format="yyyy-MM-dd"
                                v-model="ruleForm.createtime"
                                style="width: 300px"
                            ></el-date-picker>
                        </el-form-item>
                        <el-form-item label="仓位：">
                            <!--<el-select
                                v-model="warehouseName"
                                @change="changeWare"
                                value-key="id"
                                filterable
                                placeholder="请选择"
                                style="width: 300px"
                            >
                                <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item">
                                    {{ item.name }}
                                </el-option>
                            </el-select>-->
                            <el-cascader
                                :options="options"
                                @change="getnode"
                                v-model="warehouseIds"
                                :props="{ checkStrictly: true ,emitPath:true}"
                                clearable
                                style="width: 300px"
                            >
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入库批号：">
                            <el-input v-model="ruleForm.batch" style="width: 300px"></el-input>
                        </el-form-item>
                        <el-form-item label="采购员：" v-if="processhidden">
                            <el-select v-model="ruleForm.buyer" value-key="id" filterable placeholder="请选择" style="width: 300px">
                                <el-option v-for="item in userlist" :key="item.id" :label="item.name" :value="item.name">
                                    {{ item.name }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="入库类型：" v-if="processhidden">
                            <el-select v-model="ruleForm.purchaseType1" @change="changec" value-key="id" filterable placeholder="请选择" style="width: 300px">
                                <el-option v-for="item in typelist" :key="item.id" :label="item.name" :value="item.name">
                                    {{ item.name }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
            <div class="container" style="margin-top: 20px">
                <el-row style="margin-top: 20px">
                    <!-- 溯源入库搜索框 -->
                    <div v-if="this.ruleForm.purchaseType1 == '溯源入库'" style="margin-top: -20px">
                        <el-row style="margin-left: 30px">
                            <el-form-item label="追溯码" label-width="left">
                                <el-input placeholder="请扫描/输入追溯码" v-model="code" style="width: 300px"></el-input>
								<el-button @click="read">查询</el-button>
                            </el-form-item>
                        </el-row>

                    </div>

                    <el-table
                        v-if="this.ruleForm.inType1 == '加工入库'"
                        :data="tableData"
                        border
                        style="margin-top: 20px"
                        ref="multipleTable"
                        header-cell-class-name="table-header"
                    >
                        <el-table-column prop="productName" label="品名">
                            <template slot-scope="scope">
                                <el-input
                                    v-model="scope.row.productName"
                                    style="200px"
                                    @click.native="addproduct(scope.$index, scope.row)"
                                ></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="specs" label="规格">
                            <template slot-scope="scope">
                                <div>
                                    <el-input placeholder="请输入内容" v-model="scope.row.specs" disabled="disabled">
                                        <template slot="append">
                                            {{ scope.row.specsUnit }}
                                        </template>
                                    </el-input>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="number" label="数量">
                            <template slot-scope="scope">
                                <div>
                                    <el-input placeholder="请输入内容" v-model="scope.row.number" @change="addup(scope.$index, scope.row)">
                                        <template slot="append">
                                            {{ scope.row.numunits }}
                                        </template>
                                    </el-input>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="subtotal" label="小计">
                            <template slot-scope="scope">
                                <div>
                                    <el-input placeholder="请输入内容" disabled="disabled" v-model="scope.row.subtotal">
                                        <template slot="append">
                                            {{ scope.row.numunits1 }}
                                        </template>
                                    </el-input>
                                </div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="processBatch" label="分包批号">
                            <template slot-scope="scope">
                                <div>
                                    <el-input placeholder="请输入内容" v-model="scope.row.sourceBatch" disabled="disabled"></el-input>
                                </div>
                            </template>
                        </el-table-column>

                    </el-table>
                    <el-table
                        v-if="this.ruleForm.inType1 == '采购入库'"
                        :data="tableData"
                        border
                        style="margin-top: 20px"
                        ref="multipleTable"
                        header-cell-class-name="table-header"
                    >
                        <!-- 非溯源入库表格 -->
                        <div v-if="this.ruleForm.purchaseType1 == '非溯源入库'">
                          <el-table-column prop="manufacturer" label="生产企业">
                              <template slot-scope="scope">
                                  <div>
                                      <el-input placeholder="请输入内容" v-model="scope.row.manufacturer"> </el-input>
                                  </div>
                              </template>
                          </el-table-column>
                            <el-table-column prop="productName" label="品名">
                                <template slot-scope="scope">
                                    <el-select
                                        v-model="scope.row.productName"
                                        value-key="id"
                                        filterable
                                        placeholder="请选择"
                                        style="width: auto"
										@change="handLeSelectname"
                                    >
                                        <el-option v-for="item in basesourcelist" :key="item.id" :label="item.name" :value="item.name">
                                            {{ item.name }}
                                        </el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column prop="specs" label="规格">
                                <template slot-scope="scope">
                                    <div>
                                        <el-input placeholder="请输入内容" v-model="scope.row.specs" disabled="disabled" style="width:300px;">
                                            <template slot="append">
												<div>
													{{scope.row.specsUnit}}
												</div>

                                            </template>
                                        </el-input>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="number" label="数量">
                                <template slot-scope="scope">
                                    <div>
                                        <el-input
                                            placeholder="请输入内容"
                                            v-model="scope.row.number"
											disabled="disabled" style="width:300px;"
                                        >
                                            <template slot="append">
                                                {{ scope.row.numunits }}
                                            </template>
                                        </el-input>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="subtotal" label="小计">
                                <template slot-scope="scope">
                                    <div>
                                        {{scope.row.specs*scope.row.number}}{{scope.row.numunits1}}
                                    </div>
                                </template>
                            </el-table-column>

                        </div>
                        <!-- 溯源入库表格 -->
                        <div v-if="this.ruleForm.purchaseType1 == '溯源入库'">
                            <el-table-column label="追溯码" prop="code">

                            </el-table-column>
							<el-table-column prop="productName" label="品名">
							    <template slot-scope="scope">
							        {{scope.row.productName}}
								</template>
							</el-table-column>
							<el-table-column prop="specs" label="规格">
							    <template slot-scope="scope">
									{{scope.row.specs}}{{scope.row.specs}}
							    </template>
							</el-table-column>
							<el-table-column prop="number" label="数量">
							    <template slot-scope="scope">
							       {{scope.row.number}}
							    </template>
							</el-table-column>
							<el-table-column prop="subtotal" label="小计">
							    <template slot-scope="scope">
							       {{scope.row.specs*scope.row.number}}
							    </template>
							</el-table-column>
							<el-table-column prop="manufacturer" label="生产企业">

							</el-table-column>
							<el-table-column prop="place" label="产地">

							</el-table-column>
                        </div>
                    </el-table>
                    <!-- <div @click="addManure" class="addManure">添加入库明细</div> -->
                </el-row>
            </div>
            <el-dialog title="请选择" customClass="1000px" :visible.sync="dialogFormVisible">
                <el-table :data="tableData1" border style="margin-top: 20px" ref="multipleTable" header-cell-class-name="table-header">
                    <el-table-column prop="productName" sortable label="品名"></el-table-column>
                    <el-table-column prop="batch" sortable label="批号"></el-table-column>
                    <el-table-column prop="totalNumber" sortable label="规格">
                        <template slot-scope="scope">
                            <!-- {{ scope.row.totalNumber }}{{ scope.row.units }}  -->
                            {{scope.row.recallSpec}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="grade" sortable label="数量">
                        <template slot-scope="scope"> {{ scope.row.subNumber}}{{ scope.row.un }} </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                        <template slot-scope="scope">
                            <el-button type="text" @click="handLeSelect(scope.$index, scope.row)">选择</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    layout="total, prev, pager, next, jumper"
                    :page-size="pagesize"
                    :current-page.sync="currentPage"
                    :total="total"
                    @current-change="handleCurrentChange"
                    style="margin-top: 20px"
                ></el-pagination>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="close">取 消</el-button>
                    <el-button type="primary" @click="save">确 定</el-button>
                </div>
            </el-dialog>

			<el-dialog title="分包" customClass="500px" :visible.sync="dialogFormVisible1">
			   <el-form label-width="120px">
				   <el-col>
				   	<el-form-item label="规格：" prop="reapNumber">
				   	    <el-input placeholder="请输入" v-model.number="sub.spec"  style="width: 200px">
				   	        <template slot="append">
				   				<!-- {{details.units}} -->
				   	            <el-select v-model="sub.specUnits"  placeholder="单位"  value-key="id"   style="width:80px !important">
				   	                <el-option v-for="item2 in unitslist" :key="item2.id" :label="item2.name" :value="item2.name">{{item2.name}}</el-option>
				   	            </el-select>
				   	        </template>
				   	    </el-input>
				   	    <!-- <el-button style="margin-left:10px">单位管理</el-button> -->
				   	</el-form-item>
				   	<el-form-item label="生产时间：">
				   	    <el-date-picker
				   	        v-model="sub.createtime"
				   	        type="date"
				   	        value-format="yyyy-MM-dd"
				   	        placeholder
				   	        style="width: 300px"
				   	    ></el-date-picker>
				   	</el-form-item>
				   	<el-form-item label="分包批次：">
				   	    <el-input v-model="sub.batch" style="width:300px;"></el-input>
				   	</el-form-item>
				   	<el-form-item label="追溯码数量：">
				   	    <el-input v-model="sub.subNumber" style="width:300px;"></el-input>
				   	</el-form-item>
				   	<el-form-item >
				   		<el-checkbox v-model="radio1">容错率5%，开启后，会增加5%的码</el-checkbox>
				   	</el-form-item>

				   </el-col>
			   </el-form>

			    <div slot="footer" class="dialog-footer">
			        <el-button @click="close1">取 消</el-button>
			        <el-button type="primary" @click="save1">确 定</el-button>
			    </div>
			</el-dialog>

            <el-form-item class="footerFixed" label-width="0px">
                <el-button type="primary" @click="submitrule('ruleForm')">提交</el-button>
                <el-button @click="backPage">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {
    supplier_findByAll,
    user_findByAll,
    basesource_findByAll,
    unit_findByList,
    storage_save,
    plot_findByAll,
    process_findByList,
    sub_findByList,
	storage_manage_sourceinfo,
	model_crop_loadbind,
	warehouse_listpart,
    warehouse_tree
} from '@/request/api';
import { soil_findByBaseId,map_findByList } from '@/request/breedApi'
export default {
    data() {
        return {
			radio1:true,
			sub:{},
			dialogFormVisible1:false,
			code:'',
            disabled: true,
            tableData1: [],
            total: 0,
            pagesize: 10,
            currentPage: 1,
            dialogFormVisible: false,
            processhidden: true,
            warehouseName: '',
            options:[],
            moke:{
					warehouseId:'',
					warehousePartId:'',
					warehousePartName:'',
					warehouseName:''
				},
            tableData: [
				{
					relateId:'',
					sourceBatch:'',
					productName:'',
					specs:'',
					specsUnit:'',
					number:0,
					manufacturer:'',
					place:'',
					address:'',
					abbreviation:''
				}
			],
            typelist: [{ name: '溯源入库' }, { name: '非溯源入库' }],

            radio: 1,
            ruleForm: {
				warehouseId:'',
				warehousePartId:'',
				warehousePartName:'',
				warehouseName:'',
				inType:'',
				supplierName:'',
				batch:'',
				buyer:'',
				purchaseType:'',
                inType1: '采购入库',

				creatTime:''
            },
            rules: {},
            supplierlist: [],
            userlist: [],
            basesourcelist: [],
            unitslist: [],
            conlist: [{ name: '一号仓库' }, { name: '二号仓库' }],
            labelPosition: 'right',
            warehouseList: [],
            index: '',
			codes:[],
            warehouseIds: []
        };
    },
    mounted() {


		// this.ruleForm.warehouseId = this.$route.query.moke.warehouseId
		// this.ruleForm.warehousePartId = this.$route.query.moke.warehousePartId
		// this.ruleForm.warehousePartName = this.$route.query.moke.warehousePartName
		// this.ruleForm.warehouseName = this.$route.query.moke.warehouseName
		// console.log(this.ruleForm)
		// this.warehouseName = {
		// 	id:this.$route.query.moke.warehousePartId,
		// 	name:this.$route.query.moke.warehousePartName
		// }
		this.init();
		this.getwawrehouseList();
		this.uniqueCode();
        var d = new Date();
        var curr_date = d.getDate();
        var curr_month = d.getMonth() + 1;
        var curr_year = d.getFullYear();
        String(curr_month).length < 2 ? (curr_month = '0' + curr_month) : curr_month;
        String(curr_date).length < 2 ? (curr_date = '0' + curr_date) : curr_date;
        var yyyyMMdd = curr_year + '' + curr_month + '' + curr_date;
        this.ruleForm.batch = yyyyMMdd + Math.ceil(Math.random() * 10000);
		    this.sub.batch = yyyyMMdd + Math.ceil(Math.random() * 10000);
    },
    methods: {
        getnode(e){
				for(var s=0;s<this.options.length;s++){
					if(this.options[s].value == e[0]){
						this.moke.warehouseId = this.options[s].value
						this.moke.warehouseName = this.options[s].label
					}
					if(e.length>1){
						for(var r=0;r<this.options[s].children.length;r++){
							if(this.options[s].children[r].value == e[1]){
								this.moke.warehousePartId = this.options[s].children[r].value
								this.moke.warehousePartName = this.options[s].children[r].label
                this.ruleForm.warehouseId = this.options[s].children[r].value
                this.ruleForm.warehouseName = this.options[s].children[r].label
							}
						}
					}
				}
                console.log(this.ruleForm)
				// console.log(this.moke)
				// this.init()
				// console.log(this.warehouseId)
			},
		handLeSelectname(){
			this.dialogFormVisible1 = true
		},
		close1(){
			this.dialogFormVisible1 = false
			this.tableData[0].productName = ""
		},
		save1(){
			this.dialogFormVisible1 = false

			this.tableData[0].specs = this.sub.spec
			this.tableData[0].specsUnit = this.sub.specUnits
			this.tableData[0].number = this.sub.subNumber
			this.tableData[0].createtime = this.sub.createtime
			this.tableData[0].batch = this.sub.batch
			this.tableData[0].sourceBatch = this.sub.batch
			if(this.radio1 == true){
				this.sub.isOk = 1
			}else{
				this.sub.isOk = 0
			}
			var r = this.tableData[0].specsUnit;
			var site = r.lastIndexOf('/');
			this.tableData[0].numunits = r.substring(site + 1);
			var st = r.substr(r.lastIndexOf('/', r.lastIndexOf('/') - 1) + 1);
			var str = st.lastIndexOf('/');
			this.tableData[0].numunits1 = st.substring(0, str);

		},
		changec(){
			// this.tableData = []
		},
		read(){
			storage_manage_sourceinfo(this.code).then((res)=>{
				this.tableData[0].productName = res.sub.productName
				this.tableData[0].specs = res.sub.spec
				this.tableData[0].specsUnit = res.sub.specUnits
				this.tableData[0].place = res.company.data.address
				this.tableData[0].manufacturer = res.company.data.abbreviation
				// console.log(res.company.data.address)
				// var code = []
				 this.codes.push(this.code)
				 this.tableData[0].code = this.codes
				 // console.log(this.codes)
				// this.tableData[0].productName = res.sub.productName
				this.tableData[0].number = Number(this.tableData[0].number )+1
			})
		},
        uniqueCode() {
            let data = {
                page: this.currentPage
            };
            sub_findByList(data).then((res) => {
                this.tableData1 = res.rows;
                this.total = res.total;
                for(var i=0;i<this.tableData1.length;i++){
                    var r = this.tableData1[i].specUnits;
                    var site = r.lastIndexOf('/');
                    this.tableData1[i].un = r.substring(site + 1);
                }
                console.log(this.tableData1)
            });
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.uniqueCode();
        },

        handLeSelect(index, row) {
            this.tableData[this.index].productName = row.productName;
            this.tableData[this.index].specsUnit = row.specUnits;
            this.tableData[this.index].specs = row.spec;
            this.tableData[this.index].number = row.subNumber;
            this.tableData[this.index].subNumber = row.subNumber;
            this.tableData[this.index].subtotal = row.spec * row.subNumber;
            this.tableData[this.index].sourceBatch = row.batch;
            this.tableData[this.index].relateId = row.id;

            var r = row.specUnits;
            var site = r.lastIndexOf('/');
            this.tableData[this.index].numunits = r.substring(site + 1);
            var st = r.substr(r.lastIndexOf('/', r.lastIndexOf('/') - 1) + 1);
            var str = st.lastIndexOf('/');
            this.tableData[this.index].numunits1 = st.substring(0, str);
            this.dialogFormVisible = false;
        },
        save() {},
        close() {
            this.dialogFormVisible = false;
        },
        addproduct(index, row) {
            this.dialogFormVisible = true;
            this.index = index;
        },

        getwawrehouseList() {
			// warehouse_listpart(this.ruleForm.warehouseId).then((res)=>{
			// 	this.warehouseList = res.data
			// })
			warehouse_tree("").then((res)=>{
                // this.options = res
                for(var i=0;i<res.length;i++) {
                    this.options.push({label:res[i].name,value:res[i].id,parts:res[i].cw})
                }
                for(var s=0;s<this.options.length;s++){
                    if(this.options[s].parts.length>0){
                        var list = this.options[s].parts
                        this.options[s].children = []
                        for(var r=0;r<list.length;r++){
                            this.options[s].children.push({label:list[r].name,value:list[r].id,rname:list[r].baseSoilId})
                        }
                    }
                }
            })

        },
        submitrule() {
            // this.ruleForm.storageManageDetaileds = this.tableData;
			if(this.ruleForm.inType1 == "采购入库"){
				this.ruleForm.inType = 0
			}else{
				this.ruleForm.inType = 1
			}
			if(this.ruleForm.purchaseType1 == "溯源入库"){
				this.ruleForm.purchaseType = 0
			}else if(this.ruleForm.purchaseType1 == "非溯源入库"){
				this.ruleForm.purchaseType = 1
			}

			 this.tableData[0].warehouseId = this.ruleForm.warehouseId
			 this.tableData[0].warehousePartId = this.ruleForm.warehousePartId
			 this.tableData[0].warehouseName = this.ruleForm.warehouseName
			 this.tableData[0].warehousePartName = this.ruleForm.warehousePartName
			 this.tableData[0].inType = this.ruleForm.inType
			 this.tableData[0].supplierName = this.ruleForm.supplierName
			 this.tableData[0].batch = this.ruleForm.batch
			 this.tableData[0].buyer = this.ruleForm.buyer
			 this.tableData[0].purchaseType = this.ruleForm.purchaseType
			 this.tableData[0].createtime = this.ruleForm.createtime

			let data = {
				storages:this.tableData,
				codes:this.codes,
				sub:this.sub
			}
			// console.log(this.tableData)
			// console.log(data)
            storage_save(data).then((res) => {
                this.$notify({
                    title: '提示',
                    message: '保存成功',
                    type: 'success'
                });
                this.$router.push({
                    path: '/warehouseManagement'
                });
            });
        },
        backPage() {
            this.$router.go(-1);
        },
        addup(index, row) {
            if (this.ruleForm.source == '加工入库') {
                if (row.number > row.subNumber) {
                    this.$notify({
                        title: '提示',
                        message: '入库数量不能大于分包数量',
                        type: 'info'
                    });
                }
            }
            row.subtotal = row.specs * row.number;
        },
        getunits(index, row) {
            var r = row.unit;
            var site = r.lastIndexOf('/');
            row.numunits = r.substring(site + 1);
            var st = r.substr(r.lastIndexOf('/', r.lastIndexOf('/') - 1) + 1);
            var str = st.lastIndexOf('/');
            row.numunits1 = st.substring(0, str);
        },
        init() {
            supplier_findByAll('').then((res) => {
                this.supplierlist = res.data;
            });
            user_findByAll('').then((res) => {
                this.userlist = res.data;
            });
            model_crop_loadbind('').then((res) => {
                this.basesourcelist = res.data;
            });
            unit_findByList('').then((res) => {
                this.unitslist = res.data;
            });
        },
        handletab(ele) {
            // this.tableData = [];
            if (ele == '加工入库') {
                this.processhidden = false;
            } else {
                this.processhidden = true;
            }
        },
        handleDelete(index, row) {
            this.tableData.splice(index, 1);
        },
        addManure() {
            this.tableData.push({
                productName: '',
                specs: '',
                number: '',
                subtotal: '',
                manufacturer: ''
            });
        },
        // changeWare(ele) {
        //     console.log(ele)
        //     this.ruleForm.warehouseId = ele.id;
        //     this.ruleForm.warehouseName = ele.name;
        // }
    }
};
</script>

<style scoped>
.addManure {
    border-radius: 8px;
    margin-top: 20px;
    width: 100%;
    height: 60px;
    line-height: 60px;
    text-align: center;
    font-size: 16px;
    background: #ebf5ff 100%;
}
</style>
